package cn.mw.cmdb.controller;

import cn.mw.cmdb.entity.*;
import cn.mw.cmdb.exception.WarnTitleException;
import cn.mw.cmdb.param.*;
import cn.mw.cmdb.service.AssetsManageService;
import cn.mw.cmdb.service.ServiceAction;
import cn.mw.cmdb.service.impl.*;
import cn.mw.cmdb.util.CMDBTool;
import cn.mw.cmdb.view.ViewManager;
import cn.mw.components.mongodb.anno.AutoId;
import cn.mw.components.mongodb.anno.CMDBProperty;
import cn.mw.components.mongodb.entity.CriteriaOpsType;
import cn.mw.components.mongodb.entity.SubCondition;
import cn.mw.microMonitorCommon.api.cmdb.TableIdEnum;
import cn.mw.microMonitorCommon.api.common.BaseApiService;
import cn.mw.microMonitorCommon.api.common.ResponseBase;
import cn.mw.microMonitorCommon.entity.FeatureNeedObject;
import cn.mw.microMonitorCommon.entity.ProcessPageNeed;
import cn.mw.microMonitorCommon.entity.ProcessPageNeedDesc;
import cn.mw.microMonitorCommon.entity.cmdb.MwProcessCallInstanceInfo;
import cn.mw.microMonitorCommon.entity.cmdb.MwProcessCallInstanceInfoParam;
import cn.mw.microMonitorCommon.entity.cmdb.TableHeaderItem;
import cn.mw.microMonitorCommon.param.MwModuleFieldParam;
import cn.mw.microMonitorCommon.util.SpringUtils;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.base.Strings;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static cn.mw.cmdb.entity.ModelType.Normal;
import static cn.mw.cmdb.enums.ModelViewTypeEnum.defaultView;
import static cn.mw.cmdb.param.MwRelationPropertyType.relationModelIdKey;
import static cn.mw.cmdb.param.MwRelationPropertyType.relationPropertyIdKey;
import static cn.mw.cmdb.service.impl.InstanceServiceImpl.KEY_IDS;
import static cn.mw.cmdb.service.impl.InstanceViewImpl.mwAssetTypeKey;
import static cn.mw.cmdb.util.ValConvertUtil.booleanValueConvert;
import static cn.mw.cmdb.util.ValConvertUtil.intValueConvert;
import static cn.mw.cmdb.view.ViewManager.listToPage;
import static cn.mw.cmdb.viewProcessor.ModelViewCabinetProcess.cabinetRuleType;
import static cn.mw.cmdb.viewProcessor.ModelViewCabinetProcess.cabinetRuleTypeDownKey;
import static cn.mw.cmdb.viewProcessor.ModelViewUNumProcess.deviceHeight;
import static cn.mw.components.mongodb.entity.MongoPropertyType.strValueConvert;

@RequestMapping("/processCall")
@Controller
@Tag(name = "流程调用接口")
@Slf4j
public class MwProcessCallCMDBController extends BaseApiService {

    private static final int maxPageSize = 10000;
    private CmdbServiceManage cmdbServiceManage;
    private AssetsManageService assetsManageService;
    private ViewManager viewManager;
    private static final String idsDesc = "实例id集合";
    private static final String mwStorageLocationKey = "mw_storage_location";
    private static final String MW_ASSET_TYPE_KEY = "mw_asset_type";
    private static final String mwEquipmentTypeKey = "mw_specifications";
    private static final String mwManagerKey = "mw_manager";

    private static final String defaultFlagId = "-1";
    public static final List<String> propertyCatologTypeList = Arrays.asList("基础信息", "纳管", "纳管属性");
    public static final List<String> propertyTypeList = Arrays.asList(PropertyTypeUploadFile.ID, PropertyTypeUploadImg.ID);


    public MwProcessCallCMDBController(CmdbServiceManage cmdbServiceManage, ViewManager viewManager,AssetsManageService assetsManageService) {
        this.cmdbServiceManage = cmdbServiceManage;
        this.viewManager = viewManager;
        this.assetsManageService = assetsManageService;
    }


    @PostMapping("/getModelList")
    @ResponseBody
    @Operation(summary = "获取流程使用的模型列表")
    public ResponseBase getProcessModelList(@RequestBody MwProcessModelParam param) {
        ProcessPageNeed pageNeed = new ProcessPageNeed();
        try {
            ModelSearchParam searchParam = new ModelSearchParam();
            CustomModelServiceImpl modelService = (CustomModelServiceImpl) cmdbServiceManage.getModelService(CustomModelServiceImpl.ID);
            List<ModelInfo> ret = modelService.doSelectNormalModelList(searchParam);
            IPage<ModelInfo> modelInfoIPage = listToPage(ret, param.getPageNum(), param.getPageSize());
            pageNeed.setObjectIPage(modelInfoIPage);
            List<ProcessPageNeedDesc> pageNeedDescs = new ArrayList<>();
            for (ModelInfo modelInfo : modelInfoIPage.getRecords()) {
                ProcessPageNeedDesc p = new ProcessPageNeedDesc();
                p.setId(modelInfo.getId()).setName(modelInfo.getModelName()).setDesc(modelInfo.getSpec());
                pageNeedDescs.add(p);
            }
            pageNeed.setProcessPageNeedDescList(pageNeedDescs);
        } catch (Exception e) {
            throw new WarnTitleException("process-call-model-err");
        }
        return setResultSuccess(pageNeed);
    }

    @PostMapping("/getModelFieldList")
    @ResponseBody
    @Operation(summary = "获取流程模型字段列表")
    public ResponseBase getModelFieldList(@RequestBody MwProcessModelParam param) {
        FeatureNeedObject featureNeedObject = new FeatureNeedObject();
        try {
            String modelId = param.getFileId();
            CustomModelServiceImpl modelService = (CustomModelServiceImpl) cmdbServiceManage.getModelService(CustomModelServiceImpl.ID);
            ModelInfo modelInfo = modelService.doSelectById(modelId);
            List<PropertyInfo> propertyInfoList = modelInfo.propertyListBySort(modelInfo.getPropertyInfoList());
            Field[] declaredFields = InstanceInfoExtend.class.getDeclaredFields();
            //获取父类字段
            Field[] parentDeclaredFields = InstanceInfoExtend.class.getSuperclass().getDeclaredFields();
            Field[] declaredFieldList = Stream.concat(Arrays.stream(declaredFields), Arrays.stream(parentDeclaredFields)).toArray(Field[]::new);
            for (Field field : declaredFieldList) {
                AutoId autoId = field.getAnnotation(AutoId.class);
                CMDBProperty annotation = field.getAnnotation(CMDBProperty.class);
                if (annotation != null && annotation.isShow()) {
                    String listUrl = null;
                    boolean isMap = false;
                    //属性Id
                    if (null != autoId) {
                        listUrl = "/mwapi/cmdb/processCall/getInstanceListByProcess";
                        isMap = true;
                    }
                    String propertyId = field.getName();
                    //属性类型
                    String type = field.getType().getTypeName();
                    //中文名称
                    String descName = field.getAnnotation(Schema.class) == null ? "" : field.getAnnotation(Schema.class).description();
                    featureNeedObject.addAttribute(type, propertyId, descName, false, isMap, listUrl);
                }
            }
            for (PropertyInfo info : propertyInfoList) {
                String propertyId = info.getId();
                //中文名称
                String descName = info.getName();
                //属性类型
                String type = info.getPropertyType().id;
                //是否纳入流程属性
                Boolean enableProManage = booleanValueConvert(info.getEnableProManage());
                featureNeedObject.addAttribute(type, propertyId, descName, enableProManage, false, null);
            }
            //流程需要ids字段显示
            featureNeedObject.addAttribute("String", KEY_IDS, idsDesc, false, false, null);
        } catch (Exception e) {
            throw new WarnTitleException("process-call-model-err");
        }
        return setResultSuccess(featureNeedObject);
    }

    @PostMapping("/getInstanceListByProcess")
    @ResponseBody
    @Operation(summary = "获取流程模型实例列表")
    public ResponseBase getInstanceListByProcess(@RequestBody MwProcessModelParam param) {
        InstanceSearchParam searchParam = new InstanceSearchParam();
        ProcessPageNeed pageNeed = new ProcessPageNeed();
        try {
            String modelId = param.getFileId();
            searchParam.setModelId(modelId);
            if (!Strings.isNullOrEmpty(param.getSearchKey()) && !Strings.isNullOrEmpty(param.getSearchValue())) {
                searchParam.addSubCondition(param.getSearchKey()
                        , new SubCondition(CriteriaOpsType.regex.name(), param.getSearchValue()));
            }
            List<InstanceInfo> ret = (List<InstanceInfo>) cmdbServiceManage.service(searchParam, ServiceAction.list);
            IPage<InstanceInfo> instanceInfoIPage = listToPage(ret, param.getPageNum(), param.getPageSize());
            pageNeed.setObjectIPage(instanceInfoIPage);
            List<ProcessPageNeedDesc> pageNeedDescs = new ArrayList<>();
            for (InstanceInfo instanceInfo : instanceInfoIPage.getRecords()) {
                ProcessPageNeedDesc p = new ProcessPageNeedDesc();
                p.setId(instanceInfo.getId()).setName(instanceInfo.getInstanceName()).setDesc("").setInBandIp(instanceInfo.getInBandIp());
                pageNeedDescs.add(p);
            }
            pageNeed.setProcessPageNeedDescList(pageNeedDescs);
        } catch (Exception e) {
            throw new WarnTitleException("process-call-model-err");
        }
        return setResultSuccess(pageNeed);
    }

    @PostMapping("/getInstanceListAndHeader")
    @ResponseBody
    @Operation(summary = "获取实例列表和表头数据")
    public ResponseBase getInstanceListAndHeader(@RequestBody TableSearchParam tableSearchParam) {
        MwProcessCallInstanceInfo processCallInstanceInfo = new MwProcessCallInstanceInfo();
        //通用实例字段
        tableSearchParam.setTableId(TableIdEnum.commonInstance.getCode());
        TableHeaderAndDataManage dataManage = SpringUtils.getBean(TableHeaderAndDataManage.class);
        try {
            List<TableHeaderItem> tableHeaderItems = dataManage.listHeaders(tableSearchParam);
            List<Map> list = (List<Map>) dataManage.listTableData(tableSearchParam);
            processCallInstanceInfo.setInstanceList(list);
            processCallInstanceInfo.setHeaderItems(tableHeaderItems);
        } catch (Exception e) {
            throw new WarnTitleException("process-call-model-err");
        }
        return setResultSuccess(processCallInstanceInfo);
    }


    @PostMapping("/getAssetsListAndHeader")
    @ResponseBody
    @Operation(summary = "获取资产列表表头与数据", operationId = "getAssetsListAndHeader")
    public ResponseBase<MwProcessCallInstanceInfoParam> getAssetsListAndHeader(@RequestBody MwModuleFieldParam mwModuleFieldParam) {
        MwProcessCallInstanceInfoParam result = new MwProcessCallInstanceInfoParam();

        try {
            MwProcessCallInstanceInfo instanceInfo = new MwProcessCallInstanceInfo();
            List<Map> data = new ArrayList<>();
            List<String> ids = mwModuleFieldParam.getIds();
            //工单流程特殊要求，判断ids是否含有"-1",有则将mwModuleFieldParam的data数据直接返回
            if (CollectionUtils.isNotEmpty(ids) && ids.contains(defaultFlagId)) {
                data = mwModuleFieldParam.getData();
            }

            InstanceViewImpl modelService = (InstanceViewImpl) cmdbServiceManage.getModelService(InstanceViewImpl.ID);
            instanceInfo = modelService.getInstanceListAndHeader(mwModuleFieldParam);
            List<TableHeaderItem> searchFileld = new ArrayList<>();
            if (instanceInfo != null) {
                List<TableHeaderItem> headerItems = instanceInfo.getHeaderItems();
                if (CollectionUtils.isNotEmpty(headerItems)) {
                    for (TableHeaderItem s : headerItems) {
                        if (s.getVisible()) {
                            searchFileld.add(s);
                        }
                    }
                }
            }
            if (intValueConvert(mwModuleFieldParam.getPageNum()) == 0) {
                mwModuleFieldParam.setPageNum(1);
            }
            if (intValueConvert(mwModuleFieldParam.getPageSize()) == 0) {
                mwModuleFieldParam.setPageSize(maxPageSize);
            }
            //data为空，走查询实例方法
            if (CollectionUtils.isEmpty(data)) {
                data = instanceInfo.getInstanceList();
            }
            IPage<Map> iPage = listToPage(data, mwModuleFieldParam.getPageNum(), mwModuleFieldParam.getPageSize());
            result.setSearchFileld(searchFileld);
            result.setHeaderItems(instanceInfo.getHeaderItems());
            result.setInstanceList(iPage);
        } catch (Exception e) {
            throw new WarnTitleException("getAssetsListAndHeader-call-model-err");
        }
        return setResultSuccess(result);

    }

    @PostMapping("/getSelectInfoList")
    @ResponseBody
    @Operation(summary = "获取下拉数据列表")
    public ResponseBase getSelectInfoList(@RequestBody InstanceSearchParam instanceSearchParam) throws Exception {
        InstanceServiceImpl modelService = (InstanceServiceImpl) cmdbServiceManage.getModelService(InstanceServiceImpl.ID);
        List<InstanceInfo> instanceInfoList = modelService.doSelectList(instanceSearchParam);
        Map<String, List<InstanceInfo>> mwStorageLocationMap = instanceInfoList.stream().filter(s -> s.getData() != null && !Strings.isNullOrEmpty(strValueConvert(s.getData().get(mwStorageLocationKey)))).collect(Collectors.groupingBy(s -> strValueConvert(s.getData().get(mwStorageLocationKey))));
        MwItsmInstanceParam itsmInstanceParam = new MwItsmInstanceParam();
        List<MwItsmInstanceStorageLocationParam> storageLocationList = new ArrayList<>();
        boolean isFlag = false;
        for (Map.Entry<String, List<InstanceInfo>> entryStorageLocation : mwStorageLocationMap.entrySet()) {
            String entryStorageLocationKey = entryStorageLocation.getKey();
            List<InstanceInfo> entryStorageLocationVal = entryStorageLocation.getValue();
            MwItsmInstanceStorageLocationParam storageLocationParam = new MwItsmInstanceStorageLocationParam();
            storageLocationParam.setStorageLocation(entryStorageLocationKey);
            Map<String, List<InstanceInfo>> mwAssetTypeList = entryStorageLocationVal.stream().filter(s -> s.getData() != null && !Strings.isNullOrEmpty(strValueConvert(s.getData().get(MW_ASSET_TYPE_KEY)))).collect(Collectors.groupingBy(s -> strValueConvert(s.getData().get(MW_ASSET_TYPE_KEY))));
            List<MwItsmInstanceAssetsTypeParam> assetsTypeList = new ArrayList<>();

            for (Map.Entry<String, List<InstanceInfo>> entryAssetType : mwAssetTypeList.entrySet()) {
                String entryAssetKey = entryAssetType.getKey();
                MwItsmInstanceAssetsTypeParam itsmInstanceAssetsTypeParam = new MwItsmInstanceAssetsTypeParam();
                itsmInstanceAssetsTypeParam.setAssetType(entryAssetKey);
                List<InstanceInfo> entryAssetVal = entryAssetType.getValue();
                Map<String, List<InstanceInfo>> mwEquipmentTypeList = entryAssetVal.stream().filter(s -> s.getData() != null && !Strings.isNullOrEmpty(strValueConvert(s.getData().get(mwEquipmentTypeKey)))).collect(Collectors.groupingBy(s -> strValueConvert(s.getData().get(mwEquipmentTypeKey))));
                List<MwItsmInstanceEquipmentTypeParam> equipmentTypeList = new ArrayList<>();

                for (Map.Entry<String, List<InstanceInfo>> mwEquipmentType : mwEquipmentTypeList.entrySet()) {
                    MwItsmInstanceEquipmentTypeParam itsmInstanceEquipmentTypeParam = new MwItsmInstanceEquipmentTypeParam();
                    String mwEquipmentTypeKey = mwEquipmentType.getKey();
                    itsmInstanceEquipmentTypeParam.setEquipmentType(mwEquipmentTypeKey);
                    List<InstanceInfo> managerVal = mwEquipmentType.getValue();
                    List<Object> mwManagerList = managerVal.stream().filter(s -> s.getData() != null && !Strings.isNullOrEmpty(strValueConvert(s.getData().get(mwManagerKey)))).map(s -> s.getData().get(mwManagerKey)).collect(Collectors.toList());
                    itsmInstanceEquipmentTypeParam.setManagerList(mwManagerList);
                    equipmentTypeList.add(itsmInstanceEquipmentTypeParam);
                }
                itsmInstanceAssetsTypeParam.setEquipmentTypeList(equipmentTypeList);
                if (CollectionUtils.isNotEmpty(itsmInstanceAssetsTypeParam.getEquipmentTypeList())) {
                    assetsTypeList.add(itsmInstanceAssetsTypeParam);
                }
                storageLocationParam.setAssetTypeList(assetsTypeList);
            }
            if (CollectionUtils.isNotEmpty(storageLocationParam.getAssetTypeList())) {
                storageLocationList.add(storageLocationParam);
            }
        }
        if (CollectionUtils.isNotEmpty(storageLocationList)) {
            itsmInstanceParam.setStorageLocationList(storageLocationList);
        }
        return setResultSuccess(itsmInstanceParam);
    }

    @PostMapping("/getInstanceListBrowse")
    @ResponseBody
    @Operation(summary = "根据字段查询实例列表")
    public ResponseBase getInstanceListBrowse(@RequestBody Map param) throws Exception {
        List<InstanceInfoExtend> instanceInfoExtends = assetsManageService.doSelectInstanceList(param);
        return setResultSuccess(instanceInfoExtends);
    }

    @PostMapping("/getPropertyFieldByModelId")
    @ResponseBody
    @Operation(summary = "根据模型Id查询属性字段")
    public ResponseBase getPropertyFieldByModelId(@RequestBody PropertySearchParam param) throws Exception {
        ModelPropertyServiceImpl service = (ModelPropertyServiceImpl) cmdbServiceManage.getModelService(ModelPropertyServiceImpl.ID);
        return setResultSuccess(service.getPropertyFieldByModelId(param));
    }

    @PostMapping("/getRelationDropInfo")
    @ResponseBody
    @Operation(summary = "获取关联下拉数据")
    public ResponseBase getRelationDropInfo(@RequestBody InstanceParam param) throws Exception {
        PropertyRelationInfo relationPropertyInfo = new PropertyRelationInfo();
        InstanceViewImpl service = (InstanceViewImpl) cmdbServiceManage.getModelService(InstanceViewImpl.ID);
        CustomModelServiceImpl modelService = (CustomModelServiceImpl) cmdbServiceManage.getModelService(CustomModelServiceImpl.ID);

        String relationModelId = "";
        String relationPropertyId = "";
        ModelInfo modelInfo = modelService.doSelectById(param.getModelId());
        List<PropertyInfo> propertyInfoList = modelInfo.getPropertyInfoList();
        Map<String, PropertyInfo> propertyInfoById = propertyInfoList.stream().collect(Collectors.toMap(s -> s.getId(), s -> s, (k1, k2) -> k1));
        if (propertyInfoById != null && propertyInfoById.containsKey(param.getPropertyId())) {
            PropertyInfo propertyInfo = propertyInfoById.get(param.getPropertyId());
            if (propertyInfo.getPropertyTypeRef() != null && PropertyTypeExtSingle.ID.equals(propertyInfo.getPropertyTypeRef().getTypeId())) {
                Map<String, Object> context = propertyInfo.getPropertyTypeRef().getContext();
                if (context != null) {
                    relationModelId = strValueConvert(context.get(relationModelIdKey));
                    relationPropertyId = strValueConvert(context.get(relationPropertyIdKey));
                }
            }
        }
        relationPropertyInfo.setRelationPropertyId(relationPropertyId);
        relationPropertyInfo.setRelationModelId(relationModelId);
        if (!Strings.isNullOrEmpty(param.getRelationField())) {
            relationPropertyInfo.setQueryField(param.getRelationField());
        }
        if (!Strings.isNullOrEmpty(param.getRelationFieldVal())) {
            relationPropertyInfo.setQueryValue(param.getRelationFieldVal());
        }
        List<MwRelationInstanceParam> selectDataByRelation = service.getSelectDataByRelation(relationPropertyInfo);
        return setResultSuccess(selectDataByRelation);
    }


    @PostMapping("/getCabinetUNumDrop")
    @ResponseBody
    @Operation(summary = "机柜U位数据下拉")
    public ResponseBase getCabinetUNumDrop(@RequestBody MwCabinetUNumCheckParam param) throws Exception {
        String cabinetId = param.getCabinetId();
        InstanceServiceImpl service = (InstanceServiceImpl) cmdbServiceManage.getModelService(InstanceServiceImpl.ID);
        List<MwCabinetLayoutIntegration> cabinetLayoutIntegration = service.getCabinetLayoutIntegration(Arrays.asList(cabinetId));
        List<MwCabinetDropParam> list = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(cabinetLayoutIntegration) && cabinetLayoutIntegration.get(0) != null) {
            List<MwCabinetLayoutDataLookParam> cabinetLayoutData = cabinetLayoutIntegration.get(0).getCabinetLayoutData();
            if (CollectionUtils.isNotEmpty(cabinetLayoutData)) {
                for (MwCabinetLayoutDataLookParam cabinetParam : cabinetLayoutData) {
                    MwCabinetDropParam mwCabinetDropParam = new MwCabinetDropParam();
                    mwCabinetDropParam.setIndex(cabinetParam.getIndex() + "U");
                    mwCabinetDropParam.setDisabled(Strings.isNullOrEmpty(cabinetParam.getInstanceId()) ? false : true);
                    list.add(mwCabinetDropParam);
                }
            }
        }
        return setResultSuccess(list);
    }

    @PostMapping("/getCabinetUNumCheck")
    @ResponseBody
    @Operation(summary = "单个设备U位数据占用校验")
    public ResponseBase getCabinetUNumCheck(@RequestBody MwCabinetUNumCheckParam param) throws Exception {
        String cabinetId = param.getCabinetId();
        InstanceServiceImpl service = (InstanceServiceImpl) cmdbServiceManage.getModelService(InstanceServiceImpl.ID);
        String instanceId = param.getId();
        //设备U位
        Integer UNumStart = param.getDeviceUIndex();
        //设备高度
        int deviceHeightNum = 1;
        //获取实例信息
        InstanceInfo instanceInfo = service.getInstanceInfoById(instanceId);
        if (instanceInfo != null && instanceInfo.getData() != null) {
            //获取设备高度
            deviceHeightNum = intValueConvert(instanceInfo.getData().get(deviceHeight));
        }
        String ruleType = "";
        //获取机柜信息
        InstanceInfo cabinetInfo = service.getInstanceInfoById(cabinetId);
        if (cabinetInfo != null && cabinetInfo.getData() != null) {
            //获取机柜的占用规则
            ruleType = strValueConvert(cabinetInfo.getData().get(cabinetRuleType));
        }
        int UNumEnd = 0;
        if (cabinetRuleTypeDownKey.equals(ruleType)) {
            UNumEnd = UNumStart - deviceHeightNum + 1;
        } else {
            UNumEnd = UNumStart + deviceHeightNum - 1;
        }
        int indexSmall;
        int indexBig;
        //U位数按照重小到大的顺序
        if (UNumStart >= UNumEnd) {
            indexSmall = UNumEnd;
            indexBig = UNumStart;
        } else {
            indexSmall = UNumStart;
            indexBig = UNumEnd;
        }
        boolean isFlag = false;
        MwCabinetCheckAlertParam checkAlertParam = new MwCabinetCheckAlertParam();
        String message = "";
        List<MwCabinetLayoutIntegration> cabinetLayoutIntegration = service.getCabinetLayoutIntegration(Arrays.asList(cabinetId));
        if (CollectionUtils.isNotEmpty(cabinetLayoutIntegration)) {
            List<MwCabinetLayoutDataLookParam> cabinetLayoutData = cabinetLayoutIntegration.get(0).getCabinetLayoutData();
            if (CollectionUtils.isNotEmpty(cabinetLayoutData)) {
                for (int x = indexSmall; x <= indexBig; x++) {
                    int index = (x - 1) > 0 ? (x - 1) : 0;
                    MwCabinetLayoutDataLookParam cabinetLookParam = cabinetLayoutData.get(index);
                    String instanceInfoId = cabinetLookParam.getInstanceId();
                    String instanceInfoName = cabinetLookParam.getInstanceName();
                    if ((!Strings.isNullOrEmpty(instanceInfoId)) || (!Strings.isNullOrEmpty(instanceInfoName))) {
                        isFlag = true;
                        message += "第" + x + "U已被" + instanceInfoName + "占用";
                        checkAlertParam.setMessage(message);
                        checkAlertParam.setStatus(isFlag);
                        break;
                    }
                }
            }
        }
        return setResultSuccess(checkAlertParam);
    }


    @PostMapping("/getInstance/processByModel")
    @ResponseBody
    @Operation(summary = "根据模型类型获取资产数据")
    public ResponseBase getInstanceProcessByModel(@RequestBody InstanceSearchParam instanceSearchParam) throws Exception {
        InstanceServiceImpl instanceService = (InstanceServiceImpl) cmdbServiceManage.getModelService(InstanceServiceImpl.ID);
        //模型类型查询
        instanceSearchParam.addSubCondition(CMDBTool.getFieldName(InstanceInfoExtend::getModelType)
                , new SubCondition(CriteriaOpsType.in.name(), Normal.getType()));

        if(!Strings.isNullOrEmpty(instanceSearchParam.getModelName())){
            //模型类型查询
            instanceSearchParam.addSubCondition(CMDBTool.getFieldName(InstanceInfoExtend::getModelName)
                    , new SubCondition(CriteriaOpsType.is.name(), instanceSearchParam.getModelName()));
        }
        List<InstanceInfoExtend> instanceInfos = instanceService.aggregateList(instanceSearchParam);
        Map<String, Map<String, Long>> result = instanceInfos.stream()
                .collect(Collectors.groupingBy(
                        InstanceInfoExtend::getModelName, // 先按modelName分组
                        Collectors.groupingBy(
                                s -> strValueConvert(s.getData().get(mwAssetTypeKey)), // 然后按special分组
                                Collectors.counting() // 统计每个special的数量
                        )
                ));
        List<InstanceModelParam> list = new ArrayList<>();
        for (Map.Entry<String, Map<String, Long>> entry : result.entrySet()) {
            InstanceModelParam instanceModelParam = new InstanceModelParam();
            String modelName = entry.getKey();
            List<InstanceAssetsTypeNumParam> listAssetTypeList = new ArrayList<>();
            Map<String, Long> maps = entry.getValue();
            maps.forEach((k,v)->{
                InstanceAssetsTypeNumParam assetsTypeNumParam = new InstanceAssetsTypeNumParam();
                assetsTypeNumParam.setAssetsTypeName(k);
                assetsTypeNumParam.setNum(intValueConvert(v));
                listAssetTypeList.add(assetsTypeNumParam);
            });
            instanceModelParam.setModelName(modelName);
            instanceModelParam.setAssetsTypeParams(listAssetTypeList);
            list.add(instanceModelParam);
        }
        return setResultSuccess(list);
    }


}
